package base.aqs.mylock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author chengzhang
 * 2021/9/28 14:04
 * 自定义同步器
 */
public class MyLock01 {
    static int count = 0;
    static MyLock myLock = new MyLock();

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            try {
                myLock.lock();
                for (int i = 0; i < 10000; i++) {
                    count++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                myLock.unlock();
            }
        };

        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(count);
    }

}


class MyLock {

    private static class Sync extends AbstractQueuedSynchronizer {

        @Override
        protected boolean tryAcquire(int arg) {
            return compareAndSetState(0, 1);
        }


        @Override
        protected boolean tryRelease(int arg) {
            setState(0);
            return true;
        }


        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }
    }

    private Sync sync = new Sync();

    public void lock() {
        sync.acquire(1);
    }

    public void unlock() {
        sync.release(1);
    }
}
